package com.prs.crm.dao.sys.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.sys.CodeDao;

import com.prs.crm.domain.BaseEntity;

import com.prs.crm.domain.sys.Code;
import com.prs.crm.exception.InValidException;


public class CodeDaoImpl extends BaseDaoImpl<Code> implements CodeDao {

	
	@SuppressWarnings("unchecked")
	public BaseEntity findByCode(final Code code)
	{
		 return (BaseEntity)this.getHibernateTemplate().execute(
					new HibernateCallback()
					{
						public BaseEntity doInHibernate(Session session) throws HibernateException {
							try
							{
					        	Criteria criteria = session.createCriteria(Class.forName(code.getEntityName()));
					        	//criteria.add(Restrictions.eq("code", code));
					        	List<?> result = criteria.list();
					        	if (result.size()>0)
					        		return (BaseEntity)result.get(0);
					        	else
					        		return null;
							}
							catch (Exception e)
							{
								throw new InValidException(e.getMessage());
							}
				        }   
					}
			);
	}
	@SuppressWarnings("unchecked")
	public List<Code> getAllCodes()
	{
		 return (List<Code>)this.getHibernateTemplate().execute(
					new HibernateCallback()
					{
						public Object doInHibernate(Session session) throws HibernateException {
				        	Criteria criteria = session.createCriteria(Code.class);
				       
				        	criteria.addOrder(Order.asc("id"));
				        	return criteria.list();
				        }   
					}
			);
	}


	@SuppressWarnings("unchecked")
	@Override
	public int getBackRpliceAll(final String codeplan, final String codeplan1,final String codevalue) {
		return (Integer)this.getHibernateTemplate().execute(
				new HibernateCallback()
				{
					public Object doInHibernate(Session session) throws HibernateException {
			        	Criteria criteria = session.createCriteria(Code.class);
			        	criteria.add(Restrictions.eq("codeType",codeplan));
			        	criteria.add(Restrictions.eq("codeValue",codevalue));
			        	criteria.add(Restrictions.eq("codeMolde", codeplan1));			        
			        	return criteria.list().size();
			        }   
				}
		);
	}


	

	

}
